home *** CD-ROM | disk | FTP | other *** search
- /* f g e t s
- *
- * Read a line from the specified stream. The function will read
- * characters until n-1 characters are read or a newline character
- * is read or an EOF is encountered. The string is then terminated
- * with a null character. The newline character is placed into the
- * string, unlike gets which strips the newline character. The
- * function returns the first argument, but will return the NULL
- * pointer if no character was read before EOF was read.
- *
- * Patchlevel 1.0
- *
- * Edit History:
- * 02-Sep-1989 Speed up by retrieving directly from buffer.
- */
-
- #include "stdiolib.h"
-
- /*LINTLIBRARY*/
-
- char *fgets(buf, n, fp)
-
- char *buf; /* buffer for input */
- int n; /* size of buffer */
- FILE *fp; /* stream */
-
- {
- int ch; /* character read */
- unsigned char *q; /* input buffer pointer */
- unsigned char *s; /* output buffer */
- unsigned int bytesleft; /* bytes left in current load */
-
- if (n <= 1)
- return n > 0 ? (buf[0] = 0, buf) : NULL;
-
- if (fp == stdin && TESTFLAG(stdout, _IOLBF))
- (void) fflush(stdout);
-
- for (s = (unsigned char *) buf, --n; ; ) {
- if ((bytesleft = BYTESINREADBUFFER(fp)) != 0) {
- if (bytesleft > n)
- bytesleft = n;
- n -= bytesleft;
- q = GETREADPTR(fp);
- UNROLL_DO(fgetsbytes, bytesleft, if ((*s++ = *q++) == '\n') break);
- SETREADPTR(fp, q);
- }
- *s = 0;
- if (bytesleft != 0 || n == 0)
- return buf;
- if ((ch = getc(fp)) == EOF)
- return s == (unsigned char *) buf ? NULL : buf;
- if ((*s++ = ch) == '\n' || --n == 0) {
- *s = 0;
- return buf;
- }
- }
- }
-